# -*-  codeing:utf-8 -*-

import requests
import hashlib
import re, os, sys
from http.cookies import BaseCookie
from datetime import datetime
import lxml.html as htmlparser
import globaldata
from copy import deepcopy


class cdbase():

    def __init__(self, base_url):
        self.header_base = {"Accept": "application/json,text/javascript,*/*;q=0.01"}

        self.base_url = base_url

    def get_verify(self, text):
        """
        从登录页面获取 verify code
        """
        compile_item = re.compile("id='verifyRand' value='\d+'")
        dim_string = re.search(compile_item, text).group()
        target_string = re.search("\d+", dim_string).group()
        return target_string

    def handle_pwd(self, passwd, verify):
        # 加密 密码2次
        pwd1md5 = hashlib.md5()
        pwd1md5.update(passwd.encode("utf-8"))
        pwd1_result = pwd1md5.hexdigest()
        pwd2md5 = hashlib.md5()
        pwd2md5.update((pwd1_result + verify).encode("utf-8"))
        pwd2_result = pwd2md5.hexdigest()
        return pwd2_result

    def login(self, username, passwd):
        session = requests.session()
        con = session.get(url=self.base_url + "user-login.html")
        verify = self.get_verify(con.text)  # 获取verify
        pwd2_result = self.handle_pwd(passwd, verify)  # 加密密码

        data = {"account": username,
                "password": pwd2_result,
                "passwordStrength": 2,
                "referer": "/",
                "verifyRand": verify,
                "keeplogin": 1
                }

        con = session.post(url=self.base_url + "/user-login.html", data=data, headers=self.header_base)
        print(">>>>>login<<<<<")
        print(con.text)
        self.session = session

    def enter_qa(self):
        """
        主要是set-cookies 当前项目
        顺便设置每页数量
        """
        con = self.session.get(url=self.base_url + "qa/")
        page_dict = {"pagerTestcaseBrowse": "1000", "pagerBugBrowse": "1000",
                     "pagerTesttaskLinkcase": "1000",
                     "pagerTestsuiteLinkcase": "1000", "pagerTesttaskCases": "1000"}
        # 将页数设置加入cookie
        self.set_cookies(page_dict)

    def set_cookies(self, adddict):
        """
        chandao的cookies格式： {ip:{"/zentao/":cookies dict}}
         # 重新组装(domain/path/)
        """
        IPaddress = re.search("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", self.base_url).group()
        name = re.search("/\w+/", self.base_url).group()
        coo = BaseCookie()
        for key, value in adddict.items():
            coo[key] = value
            coo[key]["domain"] = IPaddress
            coo[key]["path"] = name
        self.session.cookies.update(coo)

    def get_bug_html(self, page=1):
        """
        获取未关闭bug列表的html内容
        """
        # con = self.session.get(url=self.base_url + "bug-browse-%d-unclosed.html" % page)
        # print("get bug...")
        # return con.text
        searchdict = {"andOr1": "AND",
                      "field1": "title",
                      "operator": "notinclude",
                      "andOr4": "AND",
                      "field4": "status",
                      "operator4": "!=",
                      "value4": "closed",
                      }

        self.set_search_query(searchdict)
        con = self.session.get(url=self.base_url + "bug-browse-1-0-bySearch-myQueryID--%s.html" % page)
        return con.text

    def write_file(self, name, text, mode="a+"):
        """
        写到当前目录下的文件中
        """
        cwdpath = os.path.abspath(__file__)
        basename = os.path.basename(__file__)
        cwdpath = cwdpath.replace(basename, "")
        filepath = cwdpath + name
        with open(filepath, mode=mode) as f:
            f.write(text)

    def parser_tr(self, html_string):
        # 将页面内容提取成tr list
        doc = htmlparser.document_fromstring(html_string)
        trs = doc.xpath("//tbody/tr")
        return trs

    def set_search_query(self, searchdict, searchtype="bug"):
        """
        设置搜索属性 ,筛选需要先设置搜索属性，再进行请求
        ：param searchdict dict
        """
        if searchtype == "bug":
            data = deepcopy(globaldata.BUGFORMDATA)
        elif searchtype == "testcase":
            data = deepcopy(globaldata.TESTCASEFORMDATA)
        else:
            raise Exception("search type error")
        data.update(searchdict)
        con = self.session.post(url=self.base_url + "search-buildQuery.html", data=data)
        code = con.status_code
        assert code == 200

    def search_bug(self, searchdict, page=1):
        # 筛选bug

        self.set_search_query(searchdict)
        con = self.session.get(url=self.base_url + "bug-browse-1-0-bySearch-myQueryID--%d" % page, )
        return con.text

    def get_case_result_record(self, num, timestamp=None):
        """
        num:用例号
        timestamp：date 对象
        """
        url = self.base_url + "testtask-results-0-%s.html" % (num)
        con = self.session.get(url=url)
        doc = htmlparser.document_fromstring(con.text)
        element = doc.xpath("//caption[@class='text-left']/strong/span/span")[0]
        total = element.text
        # try:
        #     element = doc.xpath("//div[@id='resultTip']/span")[0]
        #     failed = element.text
        # except:
        failed = "0"
        # 按时间筛选
        if timestamp:
            elements = doc.xpath("//tr[starts-with(@id,'result')]/td[2]")
            init_num = 0
            for element in elements:
                date = elements.text.split(" ")[0]
                if date >= timestamp:
                    init_num += 1
                    # date_x = datetime.strptime(date,"%Y-%m-%d")
                    # if date_x.__ge__(timestamp):
                    #     init_num =+1
        else:
            init_num = total
        return [total, failed, str(init_num)]

    def get_module_list(self, level=1):
        """
        先只做1级的
        level:遍历几级目录
        return : 字典 {"bug":"","case":""}
        """

        def demo(url):
            con = self.session.get(url=self.base_url + url)
            doc = htmlparser.document_fromstring(con.text)
            module_lis = doc.xpath("//div[@class='cell']/ul/li/a")
            module_dir = {}
            for li in module_lis:
                module_name = li.text
                module_id = li.attrib['id']
                module_dir[module_id] = module_name
            return module_dir

        # bug和case的id不一样
        url = "bug-browse-1.html"
        module_dir1 = demo(url)
        url = "testcase-browse-1.html"
        module_dir2 = demo(url)
        return {"bug": module_dir1, "case": module_dir2}

    def get_total_num(self, htmlstring):
        """
        获取当前的对象总数
        """
        doc = htmlparser.document_fromstring(htmlstring)
        try:
            pager = doc.xpath("//ul[@data-ride='pager']")[0]
            total = pager.attrib["data-rec-total"]
        except:
            return "00"
        return total

    def get_total_record(self, htmlstring):
        """
        获取当前页面所有执行次数
        """
        doc = htmlparser.document_fromstring(htmlstring)
        results_list = doc.xpath("//td[@class='c-result']/a")
        total_num = 0
        for result in results_list:
            add_num = int(result.text)
            total_num += add_num
        return total_num

    def get_case_list(self, module=None, page=1):
        """
        可以按模块查询，不能与搜索一起使用
        module: string   :"7"
        """
        if module:
            path = "testcase-browse-%d--byModule-%s.html" % (page, module)
        else:
            path = "testcase-browse-%d.html" % (page)
        con = self.session.get(url=self.base_url + path)
        case_trs = self.parser_tr(con.text)
        return case_trs

    def search_case(self, search):
        """
        搜索指定条件case
        param::   search:   dict
        """
        self.set_search_query(search, searchtype="testcase")
        con = self.session.get(url=self.base_url + "testcase-browse-1-0-bySearch-myQueryID.html")
        case_trs = self.parser_tr(con.text)
        return case_trs

    def get_case_view(self, num):
        url = self.base_url + "testcase-view-%s.html" % (num)
        con = self.session.get(url=url)
        doc = htmlparser.document_fromstring(con.text)
        return doc

    def get_task_cases(self, taskid):
        url = self.base_url + "testtask-case-%s.html" % (taskid)
        con = self.session.get(url=url)
        doc = htmlparser.document_fromstring(con.text)

        total = doc.xpath("//ul[@class='pager']")[0].attrib["data-rec-total"]
        per_page = doc.xpath("//[@class=''pager]")[0].attrib["data-rec-per-page"]
        url_demo = doc.xpath("//[@class=''pager]")[0].attrib["data-link-creator"]
        max_page = int(total) // int(per_page) + 2
        cases_list = []
        for p in range(1, max_page):
            url = self.base_url + url_demo.replace("{recPerPage}", str(per_page.replace("{page}", str(p))))

            con = self.session.get(url)
            trs = self.parser_tr(con.text)
            for tr in trs :
                case_id = tr.xpath("descendant::input[@type='checkbox']")[0].attrib["value"]
                cases_list.append(case_id)
            return cases_list

    def assign_cases(self,taskid,user,caselist):
        url = self.base_url + "testtask-batchAssign-%s.html"%(taskid)
        data = {"caseIDList[]":caselist,"assignedTo":user}
        con = self.session.post(url=url,data=data)
        return con

if __name__ == "__main__":
    aitem = cdbase("http://123.123.123.123:8080/zentao/")
    aitem.login(username="123", passwd="123")
    aitem.enter_qa()
